import React from "react";
import "./Search.scss";
import { ResSearch } from "../../../../api";
import { useState } from "react";
import { useEffect } from "react";
import { Link } from "react-router-dom";
import { setHistoryItems } from "../../../../utils/localStorage_utils";

export default function Search() {
  const [list, setList] = useState([]);
  const [value, setValue] = useState([]);
  const [history,setHistory] = useState([])
  useEffect(async () => {
    try {
      const { result: hots } = await ResSearch();
      setList(hots);
    } catch (error) {
      console.log(error);
    }
  }, []);

  useEffect(()=>{
    setHistory(renderHistory())
  },[])
  function saveHistory(e) {
    if (e.key == "Enter") {
      setHistoryItems(e.target.value);
      e.target.value = "";
      e.stopPropagation();
    }
  }
  function renderHistory() {
    let historyItem = localStorage.getItem("historyItems");
    if(historyItem){
      let newArr = historyItem.split("|").filter(Boolean);
      newArr.reverse();
      setValue(newArr);
    }
  }
  return (
    <div id="search">
      <div className="searchModule">
        <div className="enterSearch">
          <div className="inputCover">
            <i className="searchIcon"></i>
            <input
              className="input"
              type="search"
              placeholder="搜索歌曲、歌手、专辑"
              defaultValue=""
              onKeyDown={(e) => {
                saveHistory(e);
              }}
            />
            {/* <label className="holder">搜索歌曲、歌手、专辑</label> */}
            {/* <span className="clearInput">x</span> */}
          </div>
        </div>
        <div className="showSearch">
          <div className="netSearch">
            <h5 className="title">热门搜索</h5>
            <ul className="lists">
              {list.hots &&
                list.hots.map((item) => (
                  <li className="list" key={Math.random()}>
                    <Link className="link" to="/song">
                      {item.first}
                    </Link>
                  </li>
                ))}
            </ul>
          </div>
          <div className="localSearch">
            {value.map((item) => {
              return <div key={Math.random()}>{item}</div>;
            })}
          </div>
        </div>
      </div>
    </div>
  );
}
